package xyz.chaobei.mall.security.component;

import cn.hutool.core.util.URLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * 动态数据源，用于查询用户具有的资源信息
 *
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2021/1/12
 */
@Component
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, ConfigAttribute> storeSource = null;

    @Autowired
    private DynamicAccessDecisionService decisionService;

    @PostConstruct
    public void loadSource() {
        storeSource = decisionService.loadDataSource();
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        if (storeSource == null) this.loadSource();

        FilterInvocation filterInvocation = (FilterInvocation) object;

        String url = filterInvocation.getRequestUrl();
        String path = URLUtil.getPath(url);

        PathMatcher pathMatcher = new AntPathMatcher();
        List<ConfigAttribute> result = new LinkedList<>();

        for (Map.Entry<String, ConfigAttribute> item : storeSource.entrySet()) {
            if (pathMatcher.match(item.getKey(),path)) {
                result.add(item.getValue());
            }
        }
        return result;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
